import { Input, Select, Space, DatePicker, Flex, Upload, Button, InputNumber, Modal, message } from 'antd';
import type { DatePickerProps, InputNumberProps, UploadFile } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { useState } from 'react';
import dayjs from 'dayjs';
import '../../assets/css/Drugs/drugConsume.css'
import { handleAddDrugs } from '../../api/Drugs/DrugsApi'
import { getAddDrugsList } from '../../stores/drugsManage'
import { useDispatch } from 'react-redux';
import { RcFile } from 'antd/es/upload';

const dateFormat = 'YYYY-MM-DD';

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });

export default function DrugConsume() {
    const [drugsnameValue, setDrugsnameValue] = useState('')
    const [sortValue, setSortValue] = useState('')
    const [typeValue, setTypeValue] = useState('')
    const [startTimeValue, setStartTimeValue] = useState('')
    const [endTimeValue, setEndTimeValue] = useState('')
    const [countValue, setCountValue] = useState(0)
    const [priceValue, setPriceValue] = useState(0)
    const [messageApi, contextHolder] = message.useMessage();

    const dispatch = useDispatch()
    const handleselChange = (value: string) => {
        console.log(`selected ${value}`);
        setSortValue(value)
    };
    const onStartChange: DatePickerProps['onChange'] = (date, dateString) => {
        console.log(date, dateString);
        setStartTimeValue(dateString)
    };
    const onEndChange: DatePickerProps['onChange'] = (date, dateString) => {
        console.log(date, dateString);
        setEndTimeValue(dateString)
    };

    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState("");
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [imgUrl, setImgUrl] = useState('')

    const handleCancel = () => setPreviewOpen(false);

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }
        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
    };

    const handleChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
        console.log(newFileList);

        setFileList(newFileList.slice(-1));
        setImgUrl(newFileList[0].name)
    };

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>上传药品图片</div>
        </div>
    );

    const onCountChange: InputNumberProps['onChange'] = (value) => {
        console.log('changed', value);
        setCountValue(value)
    };

    const onPriceChange: InputNumberProps['onChange'] = (value) => {
        console.log('changed', value);
        setPriceValue(value)
    };

    const handleSubCount = () => {
        if (countValue > 1) {
            setCountValue(pre => pre - 1)
        }
    }
    const handleAddCount = () => {
        setCountValue(pre => pre + 1)
    }
    const handleSubPrice = () => {
        if (priceValue > 1) {
            setPriceValue(pre => pre - 1)
        }
    }
    const handleAddPrice = () => {
        setPriceValue(pre => pre + 1)
    }

    const handleAddList = async () => {
        dispatch(getAddDrugsList({
            drugsname: drugsnameValue,
            sort: sortValue,
            img: imgUrl,
            type: typeValue,
            count: countValue,
            price: priceValue,
            starttime: startTimeValue,
            endtime: endTimeValue,
        }))

        try {
            const drugsAdd = await handleAddDrugs({
                name: drugsnameValue,
                sort: sortValue,
                type: typeValue,
                starttime: startTimeValue,
                endtime: endTimeValue,
                count: countValue,
                price: priceValue,
                img: imgUrl
            })
            console.log(drugsAdd);
            if(drugsAdd.code===1){
                messageApi.open({
                    type: 'success',
                    content: drugsAdd.msg,
                });
            }else{
                messageApi.open({
                    type: 'warning',
                    content: drugsAdd.msg,
                });
            }
        } catch (err) {
            console.log(err);
        }

    }
    return (
        <div className='DrugConsume'>
            <table className='DrugConsume-table'>
                <tbody>
                    <tr>
                        <td>医疗名称</td>
                        <td><Input className='DrugConsume-table-input' value={drugsnameValue} onChange={(e) => setDrugsnameValue(e.target.value)} placeholder="请输入物品名称" /></td>
                    </tr>
                    <tr>
                        <td>医疗分类</td>
                        <td>
                            <Space className='DrugConsume-table-add' wrap>
                                <Select
                                    defaultValue="疫苗类"
                                    style={{ width: 120 }}
                                    onChange={handleselChange}
                                    options={[
                                        { value: '疫苗类', label: '疫苗类' },
                                        { value: '耗材', label: '耗材' },
                                        { value: '药品', label: '药品' },
                                        { value: '中药', label: '中药' },
                                        { value: '西药', label: '西药' },
                                    ]}
                                />
                            </Space>
                        </td>
                    </tr>
                    <tr>
                        <td>医品规格</td>
                        <td><Input className='DrugConsume-table-input' value={typeValue} onChange={(e) => setTypeValue(e.target.value)} placeholder="请输入规格，如：100ml" /></td>
                    </tr>
                    <tr>
                        <td>生产日期</td>
                        <td>
                            <Space className='DrugConsume-table-input' direction="vertical" size={12}>
                                <DatePicker onChange={onStartChange} defaultValue={dayjs('2022/11/04', dateFormat)} format={dateFormat} />
                            </Space>
                        </td>
                    </tr>
                    <tr>
                        <td>有效日期</td>
                        <td>
                            <Space className='DrugConsume-table-input' direction="vertical" size={12}>
                                <DatePicker onChange={onEndChange} defaultValue={dayjs('2025/11/04', dateFormat)} format={dateFormat} />
                            </Space>
                        </td>
                    </tr>
                    <tr>
                        <td>入库数量</td>
                        <td>
                            <button className='sub-btn' onClick={handleSubCount}>-</button>
                            {/* <Input value={countValue} onChange={handleCount}  /> */}
                            <InputNumber className='DrugConsume-table-add' min={1} max={99999} defaultValue={0} value={countValue} onChange={onCountChange} />
                            <button className='add-btn' onClick={handleAddCount}>+</button>
                        </td>
                    </tr>
                    <tr>
                        <td>医品价格</td>
                        <td>
                            <button className='sub-btn' onClick={handleSubPrice}>-</button>
                            <InputNumber className='DrugConsume-table-add' min={1} max={99999} defaultValue={0} value={priceValue} onChange={onPriceChange} />
                            <button className='add-btn' onClick={handleAddPrice}>+</button>
                        </td>
                    </tr>
                    <tr>
                        <td>医疗图片</td>
                        <td>
                            <Flex className='DrugConsume-table-add' gap="middle" wrap>
                                {/* <Upload
                                    action={"http://127.0.0.1:21099/users/uploadheader"}
                                    listType="picture-card"
                                    fileList={file ? [file] : []}
                                    onPreview={handlePreview}
                                    method="POST"
                                    maxCount={1} // 限制只能上传一个文件
                                    onChange={handleChange}
                                >
                                    {file ? null : uploadButton}
                                </Upload>
                                <Modal
                                    open={previewOpen}
                                    title={previewTitle}
                                    footer={null}
                                    onCancel={handleCancel}
                                >
                                    <img alt="example" style={{ width: "100%" }} src={previewImage} />
                                </Modal> */}
                                <Upload
                                    action="http://127.0.0.1:21099/users/uploadheader"
                                    listType="picture-card"
                                    fileList={fileList}
                                    method="POST"
                                    onPreview={handlePreview}
                                    onChange={handleChange}
                                    maxCount={1}
                                >
                                    {fileList.length >= 1 ? null : uploadButton}
                                </Upload>
                                <Modal open={previewOpen} title={''} footer={null} onCancel={handleCancel}>
                                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                                </Modal>
                            </Flex>
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            {contextHolder}
                            <Button type="primary" onClick={handleAddList} className='addList-btn'>确认添加</Button>
                            <Button type='default' className='goto-next'>返回上一级</Button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    )
}
